package com.vvlive.caibao.smartcity.adapter;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;

import com.squareup.picasso.Picasso;
import com.vvlive.caibao.smartcity.bean.Image;
import com.vvlive.caibao.smartcity.bean.Moment;
import com.vvlive.caibao.smartcity.ui.PersonalMomentsActivity;
import com.vvlive.caibao.smartcity.utils.ScreenUtil;
import com.vvlive.caibao.smartcity.utils.ViewAnimatorUtil;
import com.vvlive.caibao.smartcity.view.RoundImageView;
import com.vvlive.caibao.smartcity.view.ninelayout.NineGridAdapter;
import com.vvlive.caibao.smartcity.view.ninelayout.NineGridlayout;

import org.kymjs.kjframe.KJBitmap;

import java.util.List;

import smartcity.vvlive.caibao.com.smartc.R;

/**
 * Created by zhj on 2015/7/10.
 * 朋友圈adapter
 */
public class MomentsRecyclerAdapter extends RecyclerView.Adapter implements View.OnClickListener {

    private final String TAG = "Moments";

    private final int IS_HEADER = 0;
    private final int IS_ITEM = 1;

    private final int DEFAULT_MARGIN_LEFT = 16;
    private final int DEFAULT_MARGIN_RIGHT = 16;
    private final int DEFAULT_MARGIN_TOP = 8;

    private final int AVATAR_WRAPPER_START_POSITION = -150;
    private final int AVATAR_WRAPPER_FADE_IN_DURATION = 800;
    private final int AVATAR_WRAPPER_SLIDE_DOWN_DURATION = 600;

    private int marginLeft, marginTop, marginRight, marginBottom;

    private NineGridItemClickListener nineListener;
    private OnItemClickListener onItemClickListener;
    private ItemViewClickListener itemViewClickListener;
    private HeaderViewClickListener headerViewClickListener;

    private LayoutParams marginLayoutParams;
    private KJBitmap kjBitmap;
    private List<Moment> moments;
    private Context context;
    private ScreenUtil mScreenUtil;

    public MomentsRecyclerAdapter(List<Moment> moments, Context context) {
        this.moments = moments;
        this.context = context;
        kjBitmap = new KJBitmap();
        mScreenUtil = new ScreenUtil(context);
        marginLeft = (int) mScreenUtil.dip2px(DEFAULT_MARGIN_LEFT);
        marginTop = (int) mScreenUtil.dip2px(DEFAULT_MARGIN_TOP);
        marginRight = (int) mScreenUtil.dip2px(DEFAULT_MARGIN_RIGHT);
        marginLayoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, 1);
        marginLayoutParams.setMargins(marginLeft, marginTop, marginRight, 0);
        itemViewClickListener = new ItemViewClickListener();
        headerViewClickListener = new HeaderViewClickListener();
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == IS_HEADER) {
            View header = LayoutInflater.from(context).inflate(R.layout.view_moments_headerview, null);
            return new HeaderViewHolder(header);
        } else if (viewType == IS_ITEM) {
            View content = LayoutInflater.from(context).inflate(R.layout.card_moment, null);
            return new ItemViewHolder(content);
        } else {
            return null;
        }
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

        if (position != IS_HEADER) {

            Moment moment = moments.get(position - 1);
            ItemViewHolder viewHolder = (ItemViewHolder) holder;
            View itemView = viewHolder.itemView;
            itemView.setLayoutParams(marginLayoutParams);
            itemView.setTag(position);
            itemView.setOnClickListener(this);  // 给当前的CardView设置点击事件
            kjBitmap.display(viewHolder.avatar, moment.getUserPortrait());
            viewHolder.name.setText(moment.getPublisherName());
            viewHolder.mood.setText(moment.getContent());
            if (!moment.getImages().isEmpty() && moment.getImages() != null) {  // 有发表图片时设置图片的适配器

                if (moment.getImages() == null || moment.getImages().isEmpty()) {
                    viewHolder.gridlayout.setVisibility(View.GONE);
                } else {
                    viewHolder.gridlayout.setVisibility(View.VISIBLE);
                    CardNineGridAdapter adapter = new CardNineGridAdapter(context, moment.getImages());
                    if (moment.getImages().size() == 1) {
                        viewHolder.gridlayout.setDefaultWidth(moment.getImages().get(0).getWidth());
                        viewHolder.gridlayout.setDefaultHeight(moment.getImages().get(0).getHeight());
                    }
                    viewHolder.gridlayout.setAdapter(adapter);
                    viewHolder.gridlayout.setOnItemClickListener(nineListener == null ? new NineGridItemClickListener() : nineListener);
                }

            }
            viewHolder.time.setText(moment.getPublishTime());

            viewHolder.admire.setTag(position);
            viewHolder.admire.setOnClickListener(itemViewClickListener);
            viewHolder.comment.setTag(position);
            viewHolder.comment.setOnClickListener(itemViewClickListener);

        }

    }

    /**
     * 条目界面的点击事件
     */
    private final class ItemViewClickListener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            int position = (int) v.getTag();
            switch (v.getId()) {
                case R.id.card_moment_admire:   // 点赞
                    log("点赞, position = " + position);
                    break;
                case R.id.card_moment_comment:  // 评论
                    log("评论, position = " + position);
                    break;
            }
        }
    }

    /**
     * 头部的点击事件
     */
    private final class HeaderViewClickListener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.moment_header_avatar:
                    log("点击头部的头像");
                    context.startActivity(new Intent(context, PersonalMomentsActivity.class));
                    break;
            }
        }
    }

    /**
     * 朋友圈图片的点击事件
     */
    private final class NineGridItemClickListener implements NineGridlayout.OnItemClickListener {

        @Override
        public void onItemClick(View view, int position) {
            // Called when you click the picture in NineGridLayout;
            Log.i("Moments", "点击了一张图片! position = " + position);
        }
    }

    @Override
    public int getItemCount() {
        return moments == null ? 1 : moments.size() + 1;    // 因为有Header，所以+1
    }

    @Override
    public int getItemViewType(int position) {
        if (position == 0) {
            return IS_HEADER;
        } else {
            return IS_ITEM;
        }
    }

    @Override
    public void onClick(View v) {
        int position = Integer.valueOf(v.getTag().toString()) - 1;
        Log.i("Moments", "CardView was clicked!" + position);
        if (onItemClickListener != null) {
            onItemClickListener.onItemClick(v, position);
        }
    }

    /**
     * 条目的点击事件
     */
    public interface OnItemClickListener {
        void onItemClick(View v, int position);
    }

    /**
     * 设置条目的点击事件
     *
     * @param onItemClickListener
     */
    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }

    /**
     * 朋友圈条目ViewHolder
     */
    private final class ItemViewHolder extends RecyclerView.ViewHolder {

        public View itemView;   // 条目界面
        public ImageView avatar;    // 头像
        public TextView name;   // 昵称
        public TextView mood;   // 心情
        public NineGridlayout gridlayout;   // 图片
        public TextView time;   // 发表时间
        public TextView admire; // 点赞
        public TextView comment;    // 评论

        public ItemViewHolder(View itemView) {
            super(itemView);
            this.itemView = itemView;
            avatar = (ImageView) itemView.findViewById(R.id.card_moment_avatar);
            name = (TextView) itemView.findViewById(R.id.card_moment_name);
            mood = (TextView) itemView.findViewById(R.id.card_moment_mood);
            gridlayout = (NineGridlayout) itemView.findViewById(R.id.card_iv_ngrid_layout);
            time = (TextView) itemView.findViewById(R.id.card_moment_time);
            admire = (TextView) itemView.findViewById(R.id.card_moment_admire);
            comment = (TextView) itemView.findViewById(R.id.card_moment_comment);
        }
    }

    /**
     * 朋友圈头部ViewHolder
     */
    private final class HeaderViewHolder extends RecyclerView.ViewHolder {

        public ImageView headerBg;
        public TextView headerName;
        public LinearLayout headerAvatarWrapper;
        public RoundImageView headerAvatar;

        public HeaderViewHolder(View itemView) {
            super(itemView);
            headerBg = (ImageView) itemView.findViewById(R.id.moment_header_bg);
            headerBg.setOnClickListener(headerViewClickListener);
//            headerName = (TextView) itemView.findViewById(R.id.moment_header_name);
            headerAvatarWrapper = (LinearLayout) itemView.findViewById(R.id.moment_header_avatar_wrapper);
            headerAvatar = (RoundImageView) itemView.findViewById(R.id.moment_header_avatar);
            headerAvatar.setOnClickListener(headerViewClickListener);

            headerAvatarWrapper.setAlpha(0);
            headerAvatarWrapper.setTranslationY(AVATAR_WRAPPER_START_POSITION);
            ViewAnimatorUtil.fade(headerAvatarWrapper, 1, AVATAR_WRAPPER_FADE_IN_DURATION).start();
            ViewAnimatorUtil.slide(headerAvatarWrapper, AVATAR_WRAPPER_SLIDE_DOWN_DURATION, 0).start();
        }
    }

    /**
     * 朋友圈图片适配器
     */
    private class CardNineGridAdapter extends NineGridAdapter {

        public CardNineGridAdapter(Context context, List list) {
            super(context, list);
        }

        @Override
        public int getCount() {
            return (list == null) ? 0 : list.size();
        }

        @Override
        public String getUrl(int position) {
            return getItem(position) == null ? null : ((Image) getItem(position)).getUrl();
        }

        @Override
        public Object getItem(int position) {
            return (list == null) ? null : list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int i, View view) {
            ImageView iv = null;
            if (view != null && view instanceof ImageView) {
                iv = (ImageView) view;
            } else {
                iv = new ImageView(context);
            }
            iv.setScaleType(ImageView.ScaleType.CENTER_CROP);
            iv.setBackgroundColor(context.getResources().getColor((android.R.color.transparent)));
            String url = getUrl(i);
            Picasso.with(context).load(getUrl(i)).placeholder(new ColorDrawable(Color.parseColor("#f5f5f5"))).into(iv);
            if (!TextUtils.isEmpty(url)) {
                iv.setTag(url);
            }
            return iv;
        }
    }

    private void log(Object msg) {
        Log.i(TAG, msg.toString());
    }

}
